﻿using System;
using System.Collections.Generic;
using System.IO;

namespace LuaVM.Controls
{
	class CSData
	{
		public string Title { get; set; }
		public string Desc { get; set; }
		public string Path { get; set; }
	}

	class CSHelper
	{		
		public List<CSData> Scripts { get; private set; } = new List<CSData>();

		public void Load(string folder)
		{
			Scripts.Clear();

			if (!Directory.Exists(folder))
			{
				return;
			}

			DirectoryInfo di = new DirectoryInfo(folder);
			FileInfo[] files = di.GetFiles("*.lua");
			foreach (FileInfo fi in files)
			{
				string title, desc;
				GetTitleAndDesc(fi.FullName, out title, out desc);
				Scripts.Add(new CSData() { Title = title, Desc = desc, Path = fi.FullName });
			}

			Scripts.Sort((x, y) => string.Compare(x.Title, y.Title));
		}

		static void GetTitleAndDesc(string path, out string title, out string desc)
		{
			title = null;
			desc = null;
			string[] lines = null;
			try
			{
				lines = File.ReadAllLines(path);
			}
			catch
			{
				lines = new string[0];
			}

			for (int i = 0; i < lines.Length && i < 30; i++)
			{
				string line = lines[i];
				int index;

				if (string.IsNullOrEmpty(title))
				{
					index = line.IndexOf("##Title:");
					if (index != -1)
					{
						title = line.Substring(index + 8).Trim();
					}
				}

				if (string.IsNullOrEmpty(desc))
				{
					index = line.IndexOf("##Desc:");
					if (index != -1)
					{
						desc = line.Substring(index + 7).Trim();
					}
				}
			}

			if (string.IsNullOrEmpty(title))
			{
				title = Path.GetFileNameWithoutExtension(path);
			}

			if (string.IsNullOrEmpty(desc))
			{
				desc = path;
			}
		}
	}
}
